package com.holly.unit.deform.api.factory;

import cn.hutool.extra.spring.SpringUtil;
import com.holly.unit.core.util.MyClassLoader;
import com.holly.unit.deform.api.pojo.tool.DesformWidget;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类描述: 转换工厂类
 *
 * @author fxr
 * @version 1.0.0
 * @date 2022/4/14 14:39
 */
@Slf4j
public class ConvertFactory {

    /**
     * 根据不同的组件类型创建不同的转换器
     *
     * @param widget
     * @return
     */
    public static FieldCommentConverter createConverter(DesformWidget widget) {
        FieldCommentConverter converter = null;
        switch (widget.getType()) {
            case SELECT_DEPART:
                converter = new SelectDepartConverter(widget);
                break;
            case SELECT_USER:
                converter = new SelectUserConverter(widget);
                break;
            case AREA_LINKAGE:
                converter = new AreaLinkageConverter(widget);
                break;
            case FILE_UPLOAD:
                converter = new FileConverter(widget);
                break;
            case IMGUPLOAD:
                converter = new PictureConverter(widget);
                break;
            case CHECKBOX:
            case SELECT:
                converter = new MultipleConverter(widget);
                break;
        }
        return converter;
    }


    public static Map<String, FieldCommentConverter> getAllConverterByFieldConfig(List<DesformWidget> widgetList) {
        Map<String, FieldCommentConverter> map = new HashMap<>();
        for (DesformWidget widget : widgetList) {
            FieldCommentConverter converter = createConverter(widget);
            if (converter == null) {
                continue;
            }
            map.put(widget.getModel(), converter);
        }
        return map;
    }

    /**
     * 根据配置的字符串 实例化FieldCommentConverter
     * 可以配置类路径/配置java bean
     *
     * @param converter
     * @return
     */
    private static FieldCommentConverter getConverterByString(String converter) {
        Object obj = null;
        if (converter.indexOf(".") > 0) {
            try {
                obj = MyClassLoader.getClassByScn(converter).newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                log.error(e.getMessage(), e);
            }
        } else {
            obj = SpringUtil.getBean(converter);
        }
        if (obj instanceof FieldCommentConverter) {
            return (FieldCommentConverter) obj;
        }
        return null;
    }

}
